/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cuong.bean;

import client.entity.Account;
import client.entity.Appointment;
import client.entity.Customer;
import client.entity.TempAppointment;
import client.entity.Worker;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.TemporalType;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import util.HibernateUtil;

/**
 *
 * @author Admin Windows 8
 */
@ManagedBean
@SessionScoped
public class LoadAppointmentBean {

    List<TempAppointment> list;
    private String fullName;
    private JasperPrint jpPrint;
    private Date dateStart;
    private Date dateEnd;

    public LoadAppointmentBean() {
    }

    public void loadForWorker(int idAccount) throws ParseException {
        int number = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        list = new ArrayList<TempAppointment>();
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session ss = factory.openSession();
        ss.getTransaction().begin();
        Worker wk = (Worker) ss.createQuery("from Worker wk where wk.account.id=" + idAccount).uniqueResult();
        this.fullName = wk.getName();
        List<Appointment> listAppoint = ss.createQuery("from Appointment as apm where apm.worker.id=" + wk.getId()+"and apm.dateTime between :start and :end")
                .setParameter("start", dateStart).setParameter("end", dateEnd).list();
        for (Appointment appointment : listAppoint) {
            TempAppointment temp = new TempAppointment();
            number++;
            temp.setIdentity(number);
            temp.setDate(dateFormat.format(appointment.getDateTime()));
            temp.setContent(appointment.getInfo());
            temp.setNameCustomer(appointment.getWorker().getName());
            list.add(temp);
        }
    }

    public List<TempAppointment> loadForCustomer(int idAccount) throws ParseException {
        int number = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");    
        list = new ArrayList<TempAppointment>();
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session ss = factory.openSession();
        ss.getTransaction().begin();
        Customer cus = (Customer) ss.createQuery("from Customer c where c.account.id=" + idAccount).uniqueResult();
        this.fullName = cus.getName();
        List<Appointment> listAppoint = ss.createQuery("from Appointment as apm where apm.customer.id=" + cus.getId()+"and apm.dateTime between :start and :end")
                .setParameter("start", dateStart).setParameter("end", dateEnd).list();
        for (Appointment appointment : listAppoint) {
            TempAppointment temp = new TempAppointment();
            number++;
            temp.setIdentity(number);
            temp.setDate(dateFormat.format(appointment.getDateTime()));
            temp.setContent(appointment.getInfo());
            temp.setNameCustomer(appointment.getWorker().getName());
            list.add(temp);
        }
        ss.getTransaction().commit();
        ss.close();
        return list;
    }

    public void viewAppointmentAction() throws ParseException {
        Account ac = (Account) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("account");
        if (ac.getRole() == true) {
            loadForCustomer(ac.getId());
        } else {
            loadForWorker(ac.getId());
        }
    }

    public List<TempAppointment> getList() {       
        return list;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public Date getDateStart() {
        return dateStart;
    }

    public void setDateStart(Date dateStart) {
        this.dateStart = dateStart;
    }

    public Date getDateEnd() {
        return dateEnd;
    }

    public void setDateEnd(Date dateEnd) {
        this.dateEnd = dateEnd;
    }

    public void setList(List<TempAppointment> list) {
        this.list = list;
    }

    public void init() throws JRException {
        ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
                .getExternalContext().getContext();
        String filePath = ctx.getRealPath("/") + "/JasperReport/reportAppointment.jasper";;
        JRBeanCollectionDataSource bcDataS = new JRBeanCollectionDataSource(list);
        Map parameters = new HashMap();
        parameters.put("fullName", this.fullName);
        //  JasperFillManager.fillReportToFile(filePath, parameters);
        jpPrint = JasperFillManager.fillReport(filePath, parameters, bcDataS);


    }

    public void PDF(ActionEvent actionEvent) throws JRException, IOException {
        init();
        HttpServletResponse respon = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        respon.addHeader("Content-disposition", "attachment; filename=report1.pdf");
        ServletOutputStream svlOutStream = respon.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jpPrint, svlOutStream);
    }

    public void XLSX(ActionEvent actionEvent) throws JRException, IOException {
        init();
        HttpServletResponse respon = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        respon.addHeader("Content-disposition", "attachment; filename=report1.xlsx");
        ServletOutputStream svlOutStream = respon.getOutputStream();
        JRXlsxExporter docExporter = new JRXlsxExporter();
        docExporter.setParameter(JRExporterParameter.JASPER_PRINT, jpPrint);
        docExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, svlOutStream);
        docExporter.exportReport();
    }
}
